<template>
  <div class="app-container">
    <el-form class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px">
      <el-row>
        <el-form-item label="权益展示名称"
          prop="privilegeShowname">
          <el-input v-model="queryParams.privilegeShowname"
            placeholder="请输入权益展示名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="状态"
          prop="status">
          <el-select v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small">
            <el-option v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 10px;">
          <el-button type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
            size="mini"
            @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>

    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['levelPrivilege:privilege:add']">新增
        </el-button>
      </el-col>

      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['levelPrivilege:privilege:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5" style="margin-left: 10px">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['levelPrivilege:privilege:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5" style="margin-left: 10px">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['levelPrivilege:privilege:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border
        v-loading="loading"
        :data="privilegeList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection"
          width="55"
          align="center" />
        <el-table-column label="权益ID"
          min-width="100"
          align="center"
          v-if="show"
          prop="privilegeUid" />
        <el-table-column label="权益名称"
          min-width="110"
          align="center"
          :show-overflow-tooltip="true"
          prop="privilegeName"
          :formatter="privilegeOptionsFormat" />
        <el-table-column label="权益类型"
          min-width="110"
          align="center"
          :show-overflow-tooltip="true"
          prop="isUpgrade">
          <template slot-scope="scope">
            <span>{{ scope.row.isUpgrade == '1' ?  '升级礼包':'普通权益' }}</span>
          </template>

        </el-table-column>
        <el-table-column label="展示名称"
          align="center"
          prop="privilegeShowname" />
        <el-table-column label="权益图标"
          align="center"
          prop="privilegeImages">
          <template slot-scope="scope">
            <el-image v-if="scope.row.privilegeImages != null && scope.row.privilegeImages != '' "
              slot="reference"
              :src="scope.row.privilegeImages"
              class="image-rows"
              :preview-src-list="[scope.row.privilegeImages]">
            </el-image>
          </template>
          <!--        <template slot-scope="scope">-->
          <!--          <el-popover-->
          <!--            v-if="scope.row.privilegeImages != null"-->
          <!--            placement="right"-->
          <!--            title=""-->
          <!--            trigger="click">-->
          <!--            <el-image slot="reference" :src="scope.row.privilegeImages" :alt="scope.row.privilegeImages" style="max-height: 45px;max-width: 45px"></el-image>-->
          <!--            <el-image :src="scope.row.privilegeImages" ></el-image>-->
          <!--          </el-popover>-->
          <!--        </template>-->
        </el-table-column>
        <el-table-column label="权益简介"
          min-width="150"
          :show-overflow-tooltip="true"
          align="center"
          prop="privilegeIntroduce" />

        <el-table-column label="状态"
          align="center"
          prop="status">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!--      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>-->
        <!-- <el-table-column label="是否为赠送类型" align="center" prop="isGiveType" :formatter="isgivetypeFormat" /> -->
        <el-table-column label="操作"
          align="center"
          class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!--          <el-button-->
            <!--            size="mini"-->
            <!--            type="text"-->
            <!--            icon="el-icon-zoom-in"-->
            <!--            @click="handleShowDetail(scope.row)"-->
            <!--            v-hasPermi="['levelPrivilege:privilege:query']"-->
            <!--          >查看-->
            <!--          </el-button>-->
            <el-button size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['levelPrivilege:privilege:edit']">修改
            </el-button>
            <el-tooltip placement="top"
              :disabled="scope.row.status =='0' && scope.row.privilegeStatus == '0' ? true:false"
              :content="scope.row.levelName ==  undefined ?  '有会员正在享受此权益或状态为有效,无法删除':scope.row.levelName+' 包含此权益,并且有会员正在享受此权益或状态为有效,无法删除' "
              effect="light">
              <span style="width:30px;margin-left: 10px">
                <el-button size="mini"
                  type="text"
                  icon="el-icon-delete"
                  :disabled="scope.row.status =='0' && scope.row.privilegeStatus == '0' ? false:true"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['levelPrivilege:privilege:remove']">删除
                </el-button>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改自定义权益对话框 -->
    <el-dialog :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body>
      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="110px">
        <el-row>
          <el-col :span="9">
            <el-form-item label="升级礼包"
              prop="isUpgrade">
              <el-select style="100%"
                v-model="form.isUpgrade"
                placeholder="请选择是否升级礼包"
                @change="isUpgradeFun">
                <el-option v-for="dict in isUpgradeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="权益名称"
              prop="privilegeName"
              v-if="form.isUpgrade">
              <el-select v-model="form.privilegeName"
                placeholder="请选择权益名称"
                v-if="form.isUpgrade == 0">
                <el-option v-for="dict in privilegeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>

              <el-select v-model="form.privilegeName"
                placeholder="请选择权益名称"
                v-if="form.isUpgrade == 1">
                <el-option v-for="dict in privilegeUpdateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="9">
            <el-form-item label="展示名称"
              prop="privilegeShowname">
              <el-input v-model="form.privilegeShowname"
                placeholder="请输入权益展示名称" />
            </el-form-item>
          </el-col>

          <el-col :span="9">
            <el-form-item label="权益单位"
              prop="platformUnit">
              <el-input v-model="form.platformUnit"
                placeholder="请输入权益单位" />
            </el-form-item>
          </el-col>
          <el-tooltip content="如打折：权益单位为 “折” "
            effect="light"
            placement="top">
            <i class="el-icon-question"
              style="margin-top: 10px; margin-left: 10px">
            </i>
          </el-tooltip>
        </el-row>

        <!-- <el-row>
          <el-col :span="9">
            <el-form-item label="赠送" prop="isGiveType">
              <el-select v-model="form.isGiveType" placeholder="请选择是否赠送">
                <el-option v-for="dict in isGiveTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row> -->

        <el-row>
          <el-col :span="24">
            <el-form-item label="权益图标">
              <imageArraySize :imageStr.sync="form.privilegeImages"
                :key="form.privilegeImages"
                ref="childs"
                :msg="'图片要求：宽高64*64，大小2M内。'"
                :size="2 * 1024 * 1024"
                :limit="1"></imageArraySize>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="权益banner图">
              <imageArraySize :imageStr.sync="form.privilegeBanner"
                :key="form.privilegeBanner"
                ref="childss"
                :msg="'图片要求：宽高560*240，大小2M内。'"
                :size="2 * 1024 * 1024"
                :limit="1"></imageArraySize>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="权益简介"
              prop="privilegeIntroduce">
              <el-input type="textarea"
                v-model="form.privilegeIntroduce"
                placeholder="请输入权益简介" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="权益对象"
              prop="privilegeObject">
              <el-input type="textarea"
                v-model="form.privilegeObject"
                placeholder="请输入权益对象" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="注意事项"
              prop="privilegeTip">
              <el-input type="textarea"
                v-model="form.privilegeTip"
                placeholder="请输入注意事项" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看自定义权益对话框 -->
    <!--    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>-->
    <!--      <el-form ref="detailForm" label-width="100px">-->
    <!--        <el-row>-->
    <!--          <el-col :span="12" v-for="(item, index) in showData" :key="index" style="margin-top:-15px">-->
    <!--            <el-form-item :label="`${item.label}：`">-->
    <!--              <span>{{ item.value }}</span>-->
    <!--            </el-form-item>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </el-form>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--             <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>-->
    <!--          </span>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { listPrivilege, getPrivilege, getPrivilegeLevelInfo, delPrivilege, addPrivilege, updatePrivilege, updateCustomerStatus } from "@/api/customer/privilege";
import ImageUpload from '@/components/ImageUpload';
import imageArraySize from "@/components/ImageUpload/imageArraySize";

import Vue from 'vue';

export default {
  name: "Privilege",
  components: {
    ImageUpload, imageArraySize
  },
  data () {
    return {
      openOptions: [
        {
          dictValue: '1',
          dictLabel: '开通'
        },
        {
          dictValue: '0',
          dictLabel: '敬请期待'
        }
      ],
      newOptions: [{
        dictValue: '1',
        dictLabel: '新权益'
      },
      {
        dictValue: '0',
        dictLabel: '正常'
      }],
      privilegeOptions: [],
      privilegeUpdateOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自定义权益表格数据
      privilegeList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      //open类型
      openType: "",
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 权益状态字典
      privilegeStatusOptions: [],
      // 是否赠送类型
      isGiveTypeOptions: [],
      // 是否升级礼包
      isUpgradeOptions: [],
      // 状态 1有效 0无效字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platformId: null,
        privilegeName: null,
        privilegeShowname: null,
        privilegeImages: null,
        privilegeIntroduce: null,
        isGiveType: null,
        privilegeStatus: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        status: null
      },
      // 表单参数
      form: {},
      //是否显示
      show: false,
      // 表单校验
      rules: {
        privilegeName: [
          { required: true, message: "权益名称不能为空", trigger: "blur" }
        ],
        privilegeShowname: [
          { required: true, message: "权益展示名称不能为空", trigger: "blur" }
        ],
        isGiveType: [
          { required: true, message: "是否赠送不能为空", trigger: "blur" }
        ],
        isUpgrade: [
          { required: true, message: "是否升级礼包不能为空", trigger: "blur" }
        ],
        isNew: [
          { required: true, message: "是否新权益不能为空", trigger: "blur" }
        ],
        isOpen: [
          { required: true, message: "是否开通不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created () {
    this.getList();
    this.getDicts("level_privilege_status").then(response => {
      this.privilegeStatusOptions = response.data;
    });
    this.getDicts("sys_data_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("is_give_type").then(response => {
      this.isGiveTypeOptions = response.data;
    });
    this.getDicts("privilege_is_upgrade").then(response => {
      this.isUpgradeOptions = response.data;
    });
    this.getDicts("customer_privilege").then(response => {
      this.privilegeOptions = response.data;
    });
    this.getDicts("customer_privilege_update").then(response => {
      this.privilegeUpdateOptions = response.data;
    });

  },
  methods: {
    isUpgradeFun (value) {
      this.form.privilegeName = null;
    },
    /** 查询自定义权益列表 */
    getList () {
      this.loading = true;
      listPrivilege(this.queryParams).then(response => {
        this.privilegeList = response.rows;
        this.privilegeList.forEach((item, index) => {
          getPrivilegeLevelInfo(item.privilegeName).then(response => {
            if (response.data != null) {
              let levelNamedata = response.data.levelName;
              let levelName = levelNamedata.replace(/,/g, " ");//空格代替逗号
              Vue.set(this.privilegeList[index], 'levelName', levelName);
            }
          })
        });
        // console.log(this.privilegeList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 权益状态字典翻译
    privilegeStatusFormat (row, column) {
      return this.selectDictLabel(this.privilegeStatusOptions, row.privilegeStatus);
    },


    privilegeOptionsFormat (row, column) {
      if (row.isUpgrade == '0') {
        return this.selectDictLabel(this.privilegeOptions, row.privilegeName);

      } else {
        return this.selectDictLabel(this.privilegeUpdateOptions, row.privilegeName);

      }
    },

    // 是否赠送字典翻译
    isgivetypeFormat (row, column) {
      return this.selectDictLabel(this.isGiveTypeOptions, row.isGiveType);
    },
    // 是否升级礼包字典翻译
    isUpgradetypeFormat (row, column) {
      return this.selectDictLabel(this.isUpgradeOptions, row.isUpgrade);
    },
    // 状态 1有效 0无效字典翻译
    statusFormat (row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        privilegeUid: null,
        platformId: null,
        privilegeName: null,
        privilegeShowname: null,
        privilegeImages: null,
        privilegeIntroduce: null,
        isGiveType: null,
        privilegeStatus: "0",
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.privilegeUid)
      this.names = selection.map(item => item.privilegeName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.status) {
            this.multiple = true;
            break;
          }
        }
      }


    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      // this.$refs.childss.onRemoveHandler(0)
      // this.$refs.childs.onRemoveHandler(0)
      this.open = true;
      this.openType = "";
      this.openType = "add";
      this.title = "添加权益";
    },
    // /** 查看详情按钮操作 **/
    // handleShowDetail(row) {
    //   this.viewOpen = true;
    //   this.viewTitle = "查看自定义权益";
    //   this.showData = [];
    //   this.columns.forEach(item => {
    //     this.showData.push({
    //       label: item.label,
    //       value: row[item.dataIndex]
    //     })
    //   })
    // },
    handCloseDetail () {
      this.viewOpen = false
      this.showData = []
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const privilegeUid = row.privilegeUid || this.ids
      getPrivilege(privilegeUid).then(response => {
        this.form = response.data;
        this.open = true;
        this.openType = "";
        this.openType = "edit";
        this.title = "修改自定义权益";
      });
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.status === "0" ? "无效" : "有效";
      this.$confirm('确定要把"' + row.privilegeShowname + '",设为' + text + '吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateCustomerStatus(row.privilegeUid, row.status);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.getList();
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$refs.childss.selectImg();
          this.$refs.childs.selectImg();
          if (this.form.privilegeUid != null) {
            updatePrivilege(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrivilege(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const privilegeUids = row.privilegeUid || this.ids;
      const privilegeShowname = row.privilegeShowname;
      this.$confirm('是否确认删除权益名称为"' + privilegeShowname + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delPrivilege(privilegeUids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('levelPrivilege/privilege/export', {
        ...this.queryParams
      }, `levelPrivilege_privilege.xlsx`)
    }
  }
};
</script>
